import React, { useState, useEffect } from "react";
import styles from "../style/ranking.module.css";
import leftImg from "../img/left.png";
import woshi from "../img/3036e3df72e8e33f907e34725b1cec6f.png";
import reack from "../img/ranking.png";
import { score_ranking } from "../api/score";
// Define interfaces for API responses and props
interface User {
  id: number;
  name: string;
  avatar: string;
  score: number;
}

interface RankingResponse {
  code: number;
  msg: string;
  data: User[];
}

interface Proof {
  token: string;
  id: number;
}

const RankingPage: React.FC = () => {
  const [dateRange, setDateRange] = useState<"week" | "month" | "year">("week");
  const [rankingData, setRankingData] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");

  useEffect(() => {
    fetchRankingData();
  }, [dateRange]);

  const fetchRankingData = async () => {
    setLoading(true);
    setError(null);

    try {
      const response = await score_ranking({
        headers: {
          token: user.data.token,
          id: user.data.id,
        },
      });

      if (response.data.code === 1) {
        setRankingData(response.data.data);
      } else if (response.data.code === 3) {
        loginOut();
      } else {
        setError(response.data.msg);
      }
    } catch (err) {
      setError("Failed to fetch ranking data");
      console.error("Error:", err);
    } finally {
      setLoading(false);
    }
  };

  const loginOut = () => {
    // Clear auth data and redirect to login
    localStorage.removeItem("token");
    localStorage.removeItem("id");
    window.location.href = "/login";
  };

  const returnLast = () => {
    window.history.back();
  };

  const handleDateChange = (range: "week" | "month" | "year") => {
    setDateRange(range);
  };

  return (
    <div className={styles.container}>
      {/* Top bar with back button */}
      <div className={styles.top}>
        <div className={styles.top_img} onClick={returnLast}>
          <img src={leftImg} alt="Back" />
        </div>
        <div className={styles.top_text}>排行榜</div>
      </div>

      {/* Main image */}
      <div className={styles.main_img}>
        <img src={reack} alt="Ranking" />
      </div>

      {/* Ranking box */}
      <div className={styles.ranking_box}>
        {/* Date range selector */}
        <div className={styles.top_date}>
          <div
            className={`${styles.date_part} ${
              dateRange === "week" ? styles.heightLight : ""
            }`}
            onClick={() => handleDateChange("week")}
          >
            本周
          </div>
          <div
            className={`${styles.date_part} ${
              dateRange === "month" ? styles.heightLight : ""
            }`}
            onClick={() => handleDateChange("month")}
          >
            本月
          </div>
          <div
            className={`${styles.date_part} ${
              dateRange === "year" ? styles.heightLight : ""
            }`}
            onClick={() => handleDateChange("year")}
          >
            今年
          </div>
        </div>

        {/* Ranking table */}
        <div className={styles.ranking_title}>
          <div className={styles.ranking}>排名</div>
          <div className={styles.avatar}>头像</div>
          <div className={styles.nikname}>姓名</div>
          <div className={styles.nikname}>积分</div>
        </div>

        {/* Ranking content */}
        <div className={styles.ranking_content}>
          {loading ? (
            <div>Loading...</div>
          ) : error ? (
            <div>{error}</div>
          ) : rankingData.length === 0 ? (
            <img className={styles.woshi} src={woshi} alt="" />
          ) : (
            rankingData.map((user, index) => (
              <div key={user.id} className={styles.ranking_item}>
                <div className={styles.ranking}>{index + 1}</div>
                <div className={styles.avatar}>
                  <img src={user.avatar} alt={user.name} />
                </div>
                <div className={styles.nikname}>{user.name}</div>
                <div className={styles.nikname}>{user.score}</div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
};

export default RankingPage;
